﻿using System;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using mojoPortal.Business;
using mojoPortal.Business.Commerce;
using mojoPortal.Business.WebHelpers;
using eStore.Business;
using eStore.Helpers;
using Resources;
using System.Collections;

namespace eStore.UI
{
    public partial class AdminOrderDetailPage : mojoBasePage
    {
        protected int pageId = -1;
        protected int moduleId = -1;
        protected Store store;
        protected Double timeOffset;
        protected CultureInfo currencyCulture = CultureInfo.CurrentCulture;
        protected Guid orderGuid = Guid.Empty;
        private Order order;
        private SiteUser orderUser;
        bool allowDeletingOrders;
        private bool canEdit;
        private eStoreConfiguration config = new eStoreConfiguration();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!canEdit)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            if (SiteUtils.SslIsAvailable()) SiteUtils.ForceSsl();

            LoadSettings();

            //string allowedRoles = "Admins;";
            //if (store != null)
            //{
            //    allowedRoles = store.StoreConfigRoles;
            //}
            //StoreSecurity.SecureAdminPage(this, allowedRoles);

            SetupCss();
            PopulateLabels();

            if (Page.IsPostBack) { return; }

            PopulateControls();

        }

        private void PopulateControls()
        {
            if (Page.IsPostBack) return;

            if ((store == null) || (order == null)) return;
            if (orderUser != null)
            {
                lblSiteUser.Text = orderUser.Name;
                lnkUser.Text = eStoreResources.ManageUserLink;
                lnkUser.NavigateUrl = SiteRoot + "/Admin/ManageUsers.aspx?userid=" + orderUser.UserId.ToString(CultureInfo.InvariantCulture);
            }

            Title = SiteUtils.FormatPageTitle(siteSettings, CurrentPage.PageName);
            lblOrderId.Text = order.OrderGuid.ToString();
            ISettingControl setting = orderStatusControl;
            setting.SetValue(order.StatusGuid.ToString());

            litSubTotal.Text = order.SubTotal.ToString("c", currencyCulture);
            litDiscount.Text = order.Discount.ToString("c", currencyCulture);
            litOrderTotal.Text = order.OrderTotal.ToString("c", currencyCulture);

            pnlDiscount.Visible = (order.Discount > 0);

            if ((order.ShippingTotal == 0) && (order.TaxTotal == 0) && (order.Discount == 0))
            {
                pnlSubTotal.Visible = false;
            }

            lblCustomerAddressLine1.Text = order.CustomerAddressLine1;
            lblCustomerCity.Text = order.CustomerCity;
            lblCustomerCompany.Text = order.CustomerCompany;
            lblCustomerCountry.Text = order.CustomerCountry;
            lblCustomerEmail.Text = order.CustomerEmail;
            lblCustomerName.Text = order.CustomerFirstName + @" " + order.CustomerLastName;
            lblCustomerPostalCode.Text = order.CustomerPostalCode;
            lblCustomerTelephoneDay.Text = order.CustomerTelephoneDay;
            lblDiscountCodes.Text = order.DiscountCodesCsv;
            pnlDiscountCodes.Visible = lblDiscountCodes.Text != string.Empty;
            lblCustomData.Text = order.CustomData;
            pnlCustomData.Visible = lblCustomData.Text != string.Empty;
            //using (IDataReader reader = order.GetProducts())
            //{
            //    rptOrderItems.DataSource = reader;
            //    rptOrderItems.DataBind();
            //}

            using (IDataReader reader = order.GetOrderProducts())
            {
                rptOrderItems.DataSource = reader;
                rptOrderItems.DataBind();
            }

            litPaymentMethod.Text = ResourceHelper.GetResourceString("eStoreResources", order.PaymentMethod);

            Control c = Page.LoadControl("~/Controls/GCheckoutLogList.ascx");
            if (c != null)
            {
                GCheckoutLogList googleLog = c as GCheckoutLogList;
                if (googleLog != null)
                {
                    googleLog.CartGuid = order.OrderGuid;
                    pnlCheckoutLog.Controls.Add(googleLog);
                }
            }

            c = Page.LoadControl("~/Controls/PayPalLogList.ascx");
            if (c != null)
            {
                PayPalLogList logList = c as PayPalLogList;
                if (logList != null)
                {
                    logList.CartGuid = order.OrderGuid;
                    pnlCheckoutLog.Controls.Add(logList);
                }
            }

            c = Page.LoadControl("~/Controls/AuthorizeNetLogList.ascx");
            if (c != null)
            {
                AuthorizeNetLogList logList = c as AuthorizeNetLogList;
                if (logList != null)
                {
                    logList.CartGuid = order.OrderGuid;
                    pnlCheckoutLog.Controls.Add(logList);
                }
            }
            c = Page.LoadControl("~/Controls/PlugNPayLogList.ascx");
            if (c != null)
            {
                PlugNPayLogList logList = c as PlugNPayLogList;
                if (logList != null)
                {
                    logList.CartGuid = order.OrderGuid;
                    pnlCheckoutLog.Controls.Add(logList);
                }
            }
        }



        void btnSaveStatusChange_Click(object sender, EventArgs e)
        {
            if (order != null)
            {
                ISettingControl setting = orderStatusControl;
                string status = setting.GetValue();
                if (status.Length == 36)
                {
                    Guid newStatusGuid = new Guid(status);
                    order.StatusGuid = newStatusGuid;
                    order.Save();

                    if ((newStatusGuid == OrderStatus.OrderStatusCancelledGuid) || (newStatusGuid == OrderStatus.OrderStatusNoneGuid))
                    {
                        CommerceReport.DeleteOrder(order.OrderGuid);
                    }
                }
            }

            WebUtils.SetupRedirect(this, Request.RawUrl);
        }


        void btnDelete_Click(object sender, EventArgs e)
        {
            CommerceReport.DeleteOrder(order.OrderGuid);
            Order.Delete(orderGuid);

            string redirectUrl = "AdminOrderHistory.aspx?pageid="
                    + pageId.ToString(CultureInfo.InvariantCulture)
                    + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            WebUtils.SetupRedirect(this, redirectUrl);


        }


        private void PopulateLabels()
        {
            lnkStoreMenu.Text = eStoreResources.StoreManagerHeading;
            lnkStoreMenu.NavigateUrl = SiteRoot + "/eStore/AdminDashboard.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkAdminOrder.Text = eStoreResources.OrderHistoryAdminLink;
            lnkAdminOrder.NavigateUrl = SiteRoot + "/eStore/AdminOrderHistory.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkCurrentPage.Text = eStoreResources.BrowsingOrders;
            lnkCurrentPage.NavigateUrl = Request.Url.ToString();
            
            ltrTitle.Text = eStoreResources.BrowsingOrders;
            Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.BrowsingOrders);

            litItemsHeader.Text = eStoreResources.OrderDetailItemsHeader;
            btnSaveStatusChange.Text = eStoreResources.OrderStatusButton;
            btnDelete.Text = eStoreResources.DeleteOrderButton;

            UIHelper.AddConfirmationDialog(btnDelete, eStoreResources.DeleteOrderWarning);

            btnBack.Text = eStoreResources.BackButtonLabel;
            btnBackBottom.Text = btnBack.Text;
            btnBack.PostBackUrl = SiteRoot + "/eStore/AdminOrderHistory.aspx?pageid=" + pageId + "&mid=" + moduleId;
            btnBackBottom.PostBackUrl = btnBack.PostBackUrl;
            
            lnkUser.Visible = WebUser.IsAdminOrContentAdminOrContentPublisher;
        }

        private void LoadSettings()
        {

            allowDeletingOrders = ConfigHelper.GetBoolProperty("eStoreAllowDeletingOrders", allowDeletingOrders);

            currencyCulture = ResourceHelper.GetCurrencyCulture(siteSettings.GetCurrency().Code);

            if (CurrentPage.ContainsModule(moduleId))
                store = StoreHelper.GetStore();

            if (store == null) { return; }

            //currencyCulture = ResourceHelper.GetCurrencyCulture(store.DefaultCurrency);

            if (orderGuid != Guid.Empty)
            {
                order = new Order(orderGuid);

                orderUser = new SiteUser(siteSettings, order.UserGuid);

                if (order.StoreGuid != store.Guid)
                    order = null;
            }


            timeOffset = SiteUtils.GetUserTimeOffset();

            btnDelete.Visible = allowDeletingOrders;

        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);
            orderGuid = WebUtils.ParseGuidFromQueryString("order", orderGuid);
            canEdit = UserCanEditModule(moduleId);

        }

        protected virtual void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("styleestore") != null) return;
            Literal cssLink = new Literal
                                  {
                                      ID = "styleestore",
                                      Text = @"<link href='"
                                             + SiteUtils.GetSkinBaseUrl()
                                             + @"styleestore.css' type='text/css' rel='stylesheet' media='screen' />"
                                  };

            stylesheet.Controls.Add(cssLink);
        }


        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            Load += Page_Load;

            btnDelete.Click += btnDelete_Click;
            btnSaveStatusChange.Click += btnSaveStatusChange_Click;

            SuppressPageMenu();


        }
        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new eStoreConfiguration(settings);
            LoadSideContent(false, false, true, true, 0);
        }


        #endregion
    }
}
